package com.haier.dreambox.demo.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import com.haier.dreambox.demo.MyApplication;
import com.haier.dreambox.demo.R;
import com.haier.dreambox.demo.bean.*;
import com.haier.dreambox.demo.bean.uplus.Device;
import com.haier.dreambox.demo.bean.uplus.DeviceVersion;
import com.haier.dreambox.demo.net.CommonRestErrorHandler;
import com.haier.dreambox.demo.net.HaierRestClientCommon;
import com.haier.dreambox.demo.persistence.DatabaseHelper;
import com.haier.dreambox.demo.utils.DialogUtil;
import com.haier.dreambox.demo.utils.MyPrefs_;
import com.haier.dreambox.demo.utils.ToastUtils;
import com.haier.dreambox.lib.usdklib.wifi.WifiUtil;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import org.androidannotations.annotations.*;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.api.BackgroundExecutor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;

/**
 * Created by smalant on 14/12/29.
 */
@EActivity(R.layout.login)
public class LoginActivity extends Activity {


    private static final String TAG = LoginActivity.class.getSimpleName();
    @Pref
    MyPrefs_ sharePref;

    @ViewById(R.id.id_button_login)
    Button button_login;

    @ViewById(R.id.id_editText_username)
    EditText et_username;

    @ViewById(R.id.id_editText_password)
    EditText et_password;

    @RestService
    HaierRestClientCommon restClient;

    @Bean
    CommonRestErrorHandler errorHandler;

    @App
    MyApplication application;

    @Bean
    ToastUtils toastUtils;

    @OrmLiteDao(helper = DatabaseHelper.class)
    RuntimeExceptionDao<Device, String> deviceDao;

    @OrmLiteDao(helper = DatabaseHelper.class)
    RuntimeExceptionDao<DeviceVersion, Integer> deviceVersionDao;

    @Click(R.id.id_button_login)
    void doLogin() {
        if(!WifiUtil.isNetworkAvailable(this)) {
            toastUtils.showShort(this,"网络不可用，请检查！");
            return;
        }
        progressDialog.show();
        login();
        getUserDevices(true);
        getHaierDeviceGateway();

    }


    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        progressDialog = DialogUtil.buildProgressDialog(this, "登录中，请稍后...", new Runnable() {
            @Override
            public void run() {
                BackgroundExecutor.cancelAll("login", true);
            }
        });

    }

    @AfterInject
    public void init() {
        restClient.setRestErrorHandler(errorHandler);
    }


    String username;
    String password;

    @Background(serial = "login_serial", id = "login")
    void login() {
        username = et_username.getText().toString().trim();
        password = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            toastUtils.showShort(this, "用户名或密码不能为空");
            return;
        }

        //默认手机号登陆 loginType:1
        LoginRequestBean requestBean =
                new LoginRequestBean(username, password, "0", "", "", "1", application.getSequenceId());
        ResponseEntity<LoginResultBean> resultBean = restClient.login(requestBean);


        if (resultBean != null && resultBean.getStatusCode() == HttpStatus.OK) {
            LoginResultBean bean = resultBean.getBody();
            if (bean != null && bean.ok()) {
                sharePref.userId().put(bean.userId);
                sharePref.accessToken().put(resultBean.getHeaders().get("accessToken").get(0));
                sharePref.lastUsername().put(username);
                sharePref.lastPassword().put(password);
            } else {
                loginFail("登陆失败:" + (bean == null ? "内容为null" : bean.error_info), true);
            }
        } else {
            if (resultBean != null) {
                loginFail("服务器错误码: " + (resultBean.getStatusCode()), true);
            } else {
                progressDialog.dismiss();
            }
        }

    }

    @UiThread
    void loginFail(String errorMsg, boolean isNeedLocalLogin) {

        toastUtils.showShort(this, errorMsg);
        progressDialog.dismiss();
        BackgroundExecutor.cancelAll("login", true);

        DialogUtil.showDialog(this, "远程登录失败",

                isNeedLocalLogin && username.equals(sharePref.lastUsername().get()) && password.equals(sharePref.lastPassword().get()) ? "本地登陆" : "",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //获取本地用户设备列表
                        getUserDevices(false);
                    }
                }, "重试", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doLogin();
                    }
                });

    }

    @Background(serial = "login_serial", id = "login")
    void getUserDevices(boolean isNetLogin) {

        if (!isNetLogin) {
            List<Device> deviceList = deviceDao.queryForAll();
            CloseableIterator<Device> iterator = deviceDao.iterator();
            while (iterator.hasNext()) {
                Log.i(TAG, "device : " + iterator.next());
            }
            Device[] devices = new Device[deviceList.size()];
            deviceList.toArray(devices);
            application.cachHaierUserDevices(devices);
            gotoHomeActivity();
            return;
        }

        GetUserDeviceListRequestBean requestBean = new GetUserDeviceListRequestBean("", "", "", "");

        ResponseEntity<GetUserDeviceListResultBean> resultBean = restClient.getUserDevices(
                application.getSequenceId(),
                requestBean.type,
                requestBean.subType,
                requestBean.specialCode,
                requestBean.typeIdentifier,
                sharePref.userId().get());

        if (resultBean != null && resultBean.getStatusCode() == HttpStatus.OK) {
            GetUserDeviceListResultBean bean = resultBean.getBody();
            if (bean != null && bean.ok()) {

                //缓存
                application.cachHaierUserDevices(bean.devices);

                //存库
                for (Device device : bean.devices) {
                    deviceDao.createOrUpdate(device);
                    Log.i(TAG, device.toString());
                }

            } else {
                loginFail("登陆失败:" + (bean == null ? "内容为null" : bean.error_info), true);
            }
        } else {
            if (resultBean != null) {
                loginFail("服务器错误码: " + (resultBean.getStatusCode()), true);
            } else {
                progressDialog.dismiss();
            }

        }

    }

    @Background(serial = "login_serial", id = "login")
    public void getHaierDeviceGateway() {

        if (!TextUtils.isEmpty(sharePref.userGateway().get())) {
            gotoHomeActivity();
            return;
        }

        HaierDeviceGateWayRequestBean requestBean = new HaierDeviceGateWayRequestBean(getIp());
        ResponseEntity<HaierDeviceGateWayResultBean> resultBean = restClient.getHaierDeviceGateway(requestBean);

        if (resultBean != null && resultBean.getStatusCode() == HttpStatus.OK) {
            HaierDeviceGateWayResultBean bean = resultBean.getBody();
            if (bean != null) {
                if (bean.ok()) {
                    sharePref.userGateway().put(bean.appAdapter.uri);
                    gotoHomeActivity();
                } else {
                    loginFail("登陆失败:" + (bean == null ? "内容为null" : bean.error_info), true);
                }
            }
        } else {
            if (resultBean != null) {
                loginFail("服务器错误码: " + (resultBean.getStatusCode()), true);
            } else {
                progressDialog.dismiss();
            }
        }
    }

    @UiThread
    void gotoHomeActivity() {
        progressDialog.dismiss();

        HomeActivity_.intent(this).start();
        finish();
    }

    private String getIp() {
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //检查Wifi状态
        if (!wm.isWifiEnabled())
            wm.setWifiEnabled(true);
        WifiInfo wi = wm.getConnectionInfo();
        //获取32位整型IP地址
        int ipAdd = wi.getIpAddress();
        //把整型地址转换成“*.*.*.*”地址
        String ip = intToIp(ipAdd);
        return ip;
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }


}
